
import React, { useEffect, useState } from 'react';
import { Button, Input, Tag, Radio, Space, Select,message } from 'antd';
import { EditOutlined,SaveOutlined } from '@ant-design/icons';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';

const {Search } = Input
import { setData, getData } from '../methods';
import { ENVDATAList } from '../const';
import { GlobalVal } from '../../global';
import { UserListApi } from '../UserList';
import Paixu from './paixu'
export const EnvComApi = {}
window.EnvComApi = EnvComApi
const App = () => {
    const [options,optionsSet] = useState([])
    const [envList, setEnvList] = useState([]);
    const [title, titleSet] = useState('');
    const [inputValue, setInputValue] = useState('');
    const [selected, selectedSet] = useState('');
    EnvComApi.envList = envList
    EnvComApi.optionsSet = optionsSet
    const handleInputChange = (e) => {
        setInputValue(e.target.value);
    };

    const handleInputConfirm = () => {
        let newTitle = title
        if (!inputValue) {
            return
        }
        if (!newTitle) {
            newTitle = inputValue.slice(0,10)
        }
        if (envList.find(item => item.href == inputValue)) {
            message.error('环境地址重复')
            return
        }
        envList.push({ title:newTitle, href:inputValue, selectedUser: '' })
        setEnvList([...envList])
        titleSet('')
        setInputValue('')
        // if (!inputValue) {
        //    return message.error('请输入地址')
        // }        
        // if (inputValue && !envList.includes(inputValue)) {
        //     setEnvList([...envList, inputValue]);
        //     setInputValue('');
        // }
    };

    const handleTagClose = (tag,index) => {
        // envList.splice(index,1)
        let newEnvList = envList.filter(item => item.href !== tag.href)
        setEnvList([...newEnvList]);
    };
    useEffect(() => {
        getData(ENVDATAList).then((envData) => {
            if (!envData || envData.length === 0) {
                envData = []
            }
            setEnvList(envData)
        })
    }, [])
    useEffect(() => {
        // 同步数据到chrome.storage.local
        setData(ENVDATAList, envList)
    }, [envList])
    const onDragEnd = (result) => {
        if (!result.destination) {
          return;
        }
    
        const newList = Array.from(envList);
        const [removed] = newList.splice(result.source.index, 1);
        newList.splice(result.destination.index, 0, removed);
    
        setEnvList(newList);
      };    
    const getEnvItem = (tag, index)=>{
        return (
            <Tag color="orange"closable onClose={() => handleTagClose(tag,index)}>
            {
                tag.edit ?
                <React.Fragment>
                    <Input
                        type="text"
                        size="small"
                        value={tag.title}
                        onChange={(e) => {
                            tag.title = e.target.value
                            setEnvList([...envList])
                        }}
                        style={{ width: '80px', marginRight: '0px' }}
                        placeholder="环境标题"
                        onPressEnter={()=>{
                            tag.edit = !tag.edit
                            setEnvList([...envList])                                                
                        }}
                    />
                    <Input
                        type="text"
                        size="small"
                        value={tag.href}
                        onChange={(e) => {
                            tag.href = e.target.value
                            setEnvList([...envList])
                        }}
                        onPressEnter={()=>{
                            tag.edit = !tag.edit
                            setEnvList([...envList])                                                
                        }}
                        style={{ width: '370px', marginRight: '0px' }}
                        placeholder="环境登录地址"
                    />
                </React.Fragment>
                :
                <React.Fragment>
                    <Button type="text" size='small' style={{ width: '80px', marginRight: '0px' ,textAlign:'left',pointerEvents:'none'}}>
                        {tag.title}
                    </Button>
                    <Button type="link" size='small' style={{ width: '370px', marginRight: '0px' ,textAlign:'left'}} onClick={()=>{
                         let url = tag.href
                         if (tag.selectedUser) {
                             let user = tag.selectedUser.split('/')
                             url += `?name=${user[0]}&pwd=${user[1]}`
                         }    
                         window.open(`${url}`, '_blank')                                              
                    }}>
                    {tag.href.split('resources')[0]}
                    </Button>                                        
                </React.Fragment>
            }
            <Select
                defaultValue={''}
                size="small"
                style={{
                    width: 120,
                    // marginLeft: 20
                }}
                placeholder={'自动登录账号'}
                onChange={(val) => {
                    tag.selectedUser = val
                    setEnvList([...envList])
                }}
                onClear={() => {
                    tag.selectedUser = ''
                    setEnvList([...envList])
                }}
                options={options}
                value={tag.selectedUser}
                allowClear
            />
            <Button size='small'  onClick={()=>{
                tag.edit = !tag.edit
                setEnvList([...envList])
            }}>{tag.edit?<SaveOutlined />:<EditOutlined/>}</Button>
        </Tag>            
        )
    }      
    return (
        <div style={{ padding: '20px' }}>
            <Input
                type="text"
                size="small"
                value={title}
                onChange={(e)=>{
                    titleSet(e.target.value)
                }}
                style={{ width: '100px', marginRight: '0' }}
                placeholder="环境标题"
            />
            <Input
                type="text"
                size="small"
                value={inputValue}
                onChange={handleInputChange}
                // onBlur={handleInputConfirm}
                onPressEnter={handleInputConfirm}
                style={{ width: '400px', marginRight: '0' }}
                placeholder="环境登录地址"
            />
            <Button size="small" onClick={handleInputConfirm} title={"添加环境的登录地址，可以选择账号，点击链接按照此账号进行登录"}>
                + 添加登录地址
            </Button>
            <div className='env-list'>
            <DragDropContext onDragEnd={onDragEnd}>
                <Droppable droppableId="list">
                    {(provided, snapshot) => (
                    <div ref={provided.innerRef} {...provided.droppableProps}>
                        {envList.map((tag, index) => (
                        <Draggable key={tag.href} draggableId={tag.href} index={index}>
                            {(provided, snapshot) => (
                            <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
                                {getEnvItem(tag, index)}
                            </div>
                            )}
                        </Draggable>
                        ))}
                        {provided.placeholder}
                    </div>
                    )}
                </Droppable>
            </DragDropContext>                
                    {/* {envList.map((tag, index) => (
                        <div key={`${index}+${tag.href}`}>
                            {getEnvItem(tag, index)}
                        </div>
                    ))} */}
                {/* <Space direction="vertical">
                </Space> */}
                {/* <Radio.Group onChange={onChange} value={selected}>
                </Radio.Group> */}
            </div>
        </div>
    );
};

export default App;